package cn.thr.ymcc.service.impl;

import cn.thr.ymcc.domain.CourseCollect;
import cn.thr.ymcc.domain.CourseSummary;
import cn.thr.ymcc.mapper.CourseCollectMapper;
import cn.thr.ymcc.mapper.CourseSummaryMapper;
import cn.thr.ymcc.result.JsonResult;
import cn.thr.ymcc.service.ICourseCollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商品收藏 服务实现类
 * </p>
 *
 * @author thr
 * @since 2023-02-28
 */
@Service
public class CourseCollectServiceImpl extends ServiceImpl<CourseCollectMapper, CourseCollect> implements ICourseCollectService {

    @Autowired
    private CourseSummaryMapper courseSummaryMapper;

    /**
     * 收藏课程，统计信息表
     * @param courseId
     * @param loginUserId
     * @return
     */
    @Override
    public JsonResult collect(Long courseId, Long loginUserId) {
        //查询
        CourseCollect courseCollect = baseMapper.selectOne(new QueryWrapper<CourseCollect>().eq("course_id", courseId)
                .eq("user_id", loginUserId));

        if(courseCollect == null){
            CourseCollect courseCollect1 = new CourseCollect()
                    .setUserId(loginUserId)
                    .setCourseId(courseId);
            baseMapper.insert(courseCollect1);

            CourseSummary courseSummary = courseSummaryMapper.selectById(courseId);
            courseSummary.setCollectCount(courseSummary.getCollectCount()+1);
            courseSummaryMapper.updateById(courseSummary);
            return JsonResult.me().setMessage("收藏成功");
        }else {
            baseMapper.deleteById(courseCollect.getId());
            CourseSummary courseSummary = courseSummaryMapper.selectById(courseId);
            courseSummary.setCollectCount(courseSummary.getCollectCount()-1);
            courseSummaryMapper.updateById(courseSummary);
            return JsonResult.me().setMessage("取消收藏成功");
        }
    }
}
